import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:memo_rcl/data/notifiers.dart';
import 'package:memo_rcl/views/title_view.dart';

import '../server/http_dio.dart';

class RegisterPage extends StatefulWidget {
  static const String id = "RegisterPage";

  const RegisterPage({super.key});

  @override
  State<RegisterPage> createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  final TextEditingController _userName = TextEditingController();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _emailVerificationCode = TextEditingController();
  final TextEditingController _password = TextEditingController();
  final TextEditingController _verificationCode = TextEditingController();

  String captchaKey = '1895780632011'; // 或从其他地方生成

  String get captchaImageUrl =>
      'http://192.168.2.13:8080/user/captcha?captchaKey=$captchaKey&_t=${DateTime.now().millisecondsSinceEpoch}';

  void refreshCaptcha() {
    setState(() {
      // 实际上只需触发 rebuild，因为 URL 中有时间戳
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfff7f7f8),
      appBar: AppBar(
        backgroundColor: Color(0xff0784dc),
        title: TitleView(title: '注册账号'),
        automaticallyImplyLeading: false, //隐藏默认的返回键
      ),
      body: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(height: 30),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 17),
              child: Text(
                '注册账号',
                style: TextStyle(
                  color: Colors.black,
                  fontSize: 35,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            SizedBox(height: 38),
            Container(
              margin: EdgeInsets.symmetric(horizontal: 15),
              padding: EdgeInsets.symmetric(horizontal: 29),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(25),
                color: Colors.white,
              ),
              height: 50,
              child: Row(
                children: [
                  Image.asset(
                    'assets/images/shoujihao_icon.png',
                    width: 20,
                    height: 20,
                  ),
                  SizedBox(width: 15),
                  Expanded(
                    child: TextField(
                      controller: _userName,
                      decoration: InputDecoration(
                        hintText: "请输入用户名",
                        hintStyle: TextStyle(
                          color: Color(0xffcb3bdc2),
                          fontSize: 16,
                        ),
                        border: InputBorder.none,
                        //去掉默认下划线
                        enabledBorder: InputBorder.none,
                        //去掉未聚焦下划线
                        focusedBorder: InputBorder.none, //去掉聚焦下划线
                      ),
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(height: 20),
            Container(
              margin: EdgeInsets.symmetric(horizontal: 15),
              padding: EdgeInsets.symmetric(horizontal: 29),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(25),
                color: Colors.white,
              ),
              height: 50,
              child: Row(
                children: [
                  Image.asset(
                    'assets/images/shoujihao_icon.png',
                    width: 20,
                    height: 20,
                  ),
                  SizedBox(width: 15),
                  Expanded(
                    child: TextField(
                      controller: _emailController,
                      decoration: InputDecoration(
                        hintText: "请输入邮箱",
                        hintStyle: TextStyle(
                          color: Color(0xffcb3bdc2),
                          fontSize: 16,
                        ),
                        border: InputBorder.none,
                        //去掉默认下划线
                        enabledBorder: InputBorder.none,
                        //去掉未聚焦下划线
                        focusedBorder: InputBorder.none, //去掉聚焦下划线
                      ),
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(height: 20),
            Container(
              margin: EdgeInsets.symmetric(horizontal: 15),
              padding: EdgeInsets.symmetric(horizontal: 29),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(25),
                color: Colors.white,
              ),
              height: 50,
              child: Row(
                children: [
                  Image.asset(
                    'assets/images/yanzhengma_icon.png',
                    width: 20,
                    height: 20,
                  ),
                  SizedBox(width: 15),
                  Expanded(
                    child: TextField(
                      controller: _emailVerificationCode,
                      decoration: InputDecoration(
                        hintText: "邮箱验证码",
                        hintStyle: TextStyle(
                          color: Color(0xffcb3bdc2),
                          fontSize: 16,
                        ),
                        border: InputBorder.none,
                        //去掉默认下划线
                        enabledBorder: InputBorder.none,
                        //去掉未聚焦下划线
                        focusedBorder: InputBorder.none, //去掉聚焦下划线
                      ),
                    ),
                  ),
                  Container(
                    height: double.infinity,
                    child: Row(
                      spacing: 24,
                      children: [
                        Container(
                          height: 20,
                          width: 1,
                          color: Color(0xffe0e0e0),
                        ),
                        GestureDetector(
                          child: ValueListenableBuilder(
                            valueListenable: emailCodeCountdown,
                            builder: (context, remainingSeconds, child) {
                              String text = remainingSeconds > 0
                                  ? '剩余${remainingSeconds}秒'
                                  : '获取验证码';
                              Color color = remainingSeconds > 0
                                  ? Colors.grey
                                  : Color(0xff0784dc);
                              return Text(
                                text,
                                style: TextStyle(fontSize: 14, color: color),
                              );
                            },
                          ),
                          onTap: () async {
                            // 如果正在倒计时，禁止点击
                            if (emailCodeCountdown.value > 0) return;

                            String email = _emailController.text.trim();
                            if (email.isEmpty) {
                              Fluttertoast.showToast(msg: '请输入邮箱！');
                              return;
                            }

                            var responseResult = await fetchVerifyCode(
                              'register',
                              email,
                            );
                            if (responseResult.code == 20000) {
                              Fluttertoast.showToast(
                                msg: responseResult.message,
                              );
                              // 启动 60 秒倒计时
                              startEmailCodeCountdown();
                            } else {
                              Fluttertoast.showToast(
                                msg: responseResult.message,
                              );
                              // 失败时不倒计时，按钮保持可点击
                            }
                          },
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(height: 20),
            Container(
              margin: EdgeInsets.symmetric(horizontal: 15),
              padding: EdgeInsets.symmetric(horizontal: 29),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(25),
                color: Colors.white,
              ),
              height: 50,
              child: Row(
                children: [
                  Image.asset(
                    'assets/images/mima_icon.png',
                    width: 20,
                    height: 20,
                  ),
                  SizedBox(width: 15),
                  Expanded(
                    child: TextField(
                      controller: _password,
                      decoration: InputDecoration(
                        hintText: "请输入密码",
                        hintStyle: TextStyle(
                          color: Color(0xffcb3bdc2),
                          fontSize: 16,
                        ),
                        border: InputBorder.none,
                        //去掉默认下划线
                        enabledBorder: InputBorder.none,
                        //去掉未聚焦下划线
                        focusedBorder: InputBorder.none, //去掉聚焦下划线
                      ),
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(height: 20),
            Container(
              margin: EdgeInsets.symmetric(horizontal: 15),
              padding: EdgeInsets.symmetric(horizontal: 29),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(25),
                color: Colors.white,
              ),
              height: 50,
              child: Row(
                children: [
                  Image.asset(
                    'assets/images/yanzhengma_icon.png',
                    width: 20,
                    height: 20,
                  ),
                  SizedBox(width: 15),
                  Expanded(
                    child: TextField(
                      controller: _verificationCode,
                      decoration: InputDecoration(
                        hintText: "验证码",
                        hintStyle: TextStyle(
                          color: Color(0xffcb3bdc2),
                          fontSize: 16,
                        ),
                        border: InputBorder.none,
                        //去掉默认下划线
                        enabledBorder: InputBorder.none,
                        //去掉未聚焦下划线
                        focusedBorder: InputBorder.none, //去掉聚焦下划线
                      ),
                    ),
                  ),
                  SizedBox(
                    height: double.infinity,
                    child: Row(
                      spacing: 24,
                      children: [
                        Container(
                          height: 20,
                          width: 1,
                          color: Color(0xffe0e0e0),
                        ),
                        GestureDetector(
                          child: Image.network(
                            captchaImageUrl,
                            height: 50,
                            width: 100,
                            fit: BoxFit.fill,
                            errorBuilder: (context, error, stackTrace) {
                              return Container(
                                height: 50,
                                width: 100,
                                color: Colors.grey,
                                child: Center(child: Text('加载失败')),
                              );
                            },
                          ),
                          onTap: () {
                            refreshCaptcha();
                          },
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(height: 30),

            Container(
              padding: EdgeInsets.symmetric(horizontal: 21),
              width: double.infinity,
              height: 65,
              child: FilledButton(
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Color(0xff0784dc)),
                ),
                onPressed: () async {
                  var userName = _userName.text.trim();
                  if (userName.isEmpty) {
                    Fluttertoast.showToast(msg: '请输入用户名！');
                    return;
                  }

                  String email = _emailController.text.trim();
                  if (email.isEmpty) {
                    Fluttertoast.showToast(msg: '请输入邮箱！');
                    return;
                  }

                  String emailVerificationCode = _emailVerificationCode.text
                      .trim();
                  if (emailVerificationCode.isEmpty) {
                    Fluttertoast.showToast(msg: '请输入邮箱验证码！');
                    return;
                  }

                  String password = _password.text.trim();
                  if (password.isEmpty) {
                    Fluttertoast.showToast(msg: '请输入密码！');
                    return;
                  }

                  String verificationCode = _verificationCode.text.trim();
                  if (verificationCode.isEmpty) {
                    Fluttertoast.showToast(msg: '请输入验证码！');
                    return;
                  }

                  var sobUser = {
                    'userName': userName,
                    'email': email,
                    'password': password,
                  };
                  var responseResult = await registerUser(
                    sobUser: sobUser,
                    emailCode: emailVerificationCode,
                    captcha: verificationCode,
                    captchaKey: captchaKey,
                  );

                  if (responseResult.code == 10000) {
                    Navigator.pop(context);
                  }
                  Fluttertoast.showToast(msg: responseResult.message);
                },
                child: Text(
                  '确认注册',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void startEmailCodeCountdown() {
    int seconds = 60;
    emailCodeCountdown.value = seconds;

    Timer.periodic(Duration(seconds: 1), (timer) {
      seconds--;
      if (seconds >= 0) {
        emailCodeCountdown.value = seconds;
      } else {
        timer.cancel();
        emailCodeCountdown.value = 0; // 恢复可点击
      }
    });
  }
}
